package com.rech.xbexpress3;

import com.rech.dialog.CustomDialog;
import com.rech.excption.MyCatchException;
import com.rech.module.AddressModule;
import com.rech.module.LogisticModule;
import com.rech.mqtt.IGetMessageCallBack;
import com.rech.mqtt.MQTTService;
import com.rech.mqtt.MyServiceConnection;
import com.rech.redis.MessageConsumer;
import com.rech.scannergun.ScannerGunManager;
import com.rech.utils.LogUtil;
import com.rech.utils.OtherUtil;
import com.rech.utils.TimeUtils;
import com.rech.utils.TimerTaskUtil;
import com.rech.websocket.WebSocketClient;
import com.tencent.bugly.crashreport.CrashReport;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Parcelable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;


import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.disposables.Disposable;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends AppCompatActivity implements IGetMessageCallBack {
    @Override
    protected void onResume() {
        super.onResume();
    }

    private synchronized void startTimeTask() {
        TimerTaskUtil.timedTask(new TimerTaskUtil.TimerTasklenster() {
            @Override
            public void onNext() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        WebSocketClient.Send("100001");
                        Log.d("WebSocketClient","发送数据：100001");
                    }
                }).start();
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                timedTask = disposable;
            }

            @Override
            public void onError() {

            }

            @Override
            public void onComplete() {
                startTimeTask();

            }
        }, 1);
    }

    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */

    private static final String DEFAULT_HOST = "127.0.0.1";
    private static final int REDIS_DEFAULT_PORT = 6379;
    private static final int WEB_DEFAULT_PORT = 9001;
    public static boolean isClient;


    private static final boolean AUTO_HIDE = true;
    private static int settingcount = 0;
    private static int activecount = 0;
    private UsbManager musbManager = null;
    private MyReceiver myReceiver = null;
    private Context mContext = null;
    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 3000L;
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private static int adcount = 0;
    private long readTimestmap = 0;
    private static int curEventCode = 0;
    private static long curLastEventTime = 0;
    public static final long EVENT_TIME_INTERVAL = 5000L;
    private Timer timer;
    private final String ACTION_USB_PERMISSION = "com.rech.xbexpress3.USB_PERMISSION";
    private TextView dateText;
    private TextView addrText;
    private TextView addrLine;
    private TextView logShow;
    private TextView sendShow;
    private TextView recShow;
    private TextView tv_cabinet_code;
    //private TextView tv_cabinet_version;
    private Button  welcome_kd_enter;
    private CustomDialog commitDialog;
    private Button btn_confirm;

    private MyServiceConnection serviceConnection;
    private MQTTService mqttService;
    ScannerGunManager scannerGunManager;
    private String expressBillNum = "";
    private Disposable timedTask;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    private boolean showLogFlag = true;
    private ImageView gzh_qrcode;
    private ImageView gz_qrcode;

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        if (orientation.equals("landscape")) {
            setContentView(R.layout.activity_fullscreen_land);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        } else {
            setContentView(R.layout.activity_fullscreen);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }
        //LogUtil.getInstance().info("Start");
        mVisible = true;
        getSupportActionBar().hide();



        readTimestmap = System.currentTimeMillis();

        //work
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        OtherUtil.setMainContext(this.getApplicationContext());
        //setContentView(R.layout.activity_fullscreen);
        RequestDevicePermission();
        mVisible = true;


//        if(OtherUtil.isServiceStarted(this,"com.xbexpress.expressnotify")){
//
//        }else{
//            OtherUtil.StartupNotify(this);
//        }
        //机器ID号
        if(OtherUtil.isExistUID(this) == false) {
            Message message = new Message();
            message.what=1;
            EventBus.getDefault().post(message);
        }else{
            String uid = OtherUtil.getUID(this);

            /*Date d = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String datestr = sf.format(d);*/
            dateText = (TextView)findViewById(R.id.date);
            addrText = (TextView)findViewById(R.id.address);
            addrLine = (TextView)findViewById(R.id.waiter);
            logShow = (TextView)findViewById(R.id.logShow);
            sendShow = (TextView)findViewById(R.id.sendShow);
            recShow = (TextView)findViewById(R.id.recShow);
            gzh_qrcode = (ImageView)findViewById(R.id.gzh_qrcode);
            gz_qrcode = (ImageView)findViewById(R.id.gz_qrcode);
            gzh_qrcode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(settingcount > 8){
                        settingcount = 0;
                        logShow.setVisibility(View.VISIBLE);
                        sendShow.setVisibility(View.VISIBLE);
                        recShow.setVisibility(View.VISIBLE);
                    }else{
                        settingcount ++;
                        logShow.setVisibility(View.INVISIBLE);
                        sendShow.setVisibility(View.INVISIBLE);
                        recShow.setVisibility(View.INVISIBLE);
                    }
                }
            });
            tv_cabinet_code = (TextView)findViewById(R.id.tv_cabinet_code);
            //tv_cabinet_version = (TextView)findViewById(R.id.tv_cabinet_version);
            tv_cabinet_code.setText(uid);
            /*try {
                tv_cabinet_version.setText("v" + OtherUtil.getVersion(this));
            } catch (Exception e) {
                e.printStackTrace();
            }*/

            logShow.setMovementMethod(ScrollingMovementMethod.getInstance());
            sendShow.setMovementMethod(ScrollingMovementMethod.getInstance());
            recShow.setMovementMethod(ScrollingMovementMethod.getInstance());
            //dateText.setText(datestr);

            //更新时间
            dateText.setText(TimeUtils.getStringDateShort(new Date()));

            IntentFilter filter=new IntentFilter();//创建意图过滤器对象
            filter.addAction(Intent.ACTION_TIME_TICK);//为接收器指定action，使之用于接收同action的广播
            registerReceiver(receiver,filter);//动态注册广播接收器

            new FetchgetCabinetType(uid).execute();
            LogUtil.getInstance().info("Start and FetchgetCabinetType");
//            SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
//            String address = sharedPreferences.getString("CabinetType_address","");
//            TextView addrText = (TextView)findViewById(R.id.address);
//            addrText.setText(address);
            new FetchHeartBeatTask().execute();
        }
        SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
        editor.putString("jj_kdysj", "");
        editor.putString("jj_ljm1", "");
        //editor.putString("jj_ljm2", "");
        //editor.putString("jj_sjr", "");
        editor.putString("jj_sfz", "");
        editor.putString("jj_name", "");
        editor.putString("jj_sjh", "");
        editor.putInt("jj_exp",0);
        editor.putInt("jj_grid",0);
        editor.putString("jj_gridtype","");
        editor.putString("jj_gridnum","");
        editor.apply();
        //work
        initControl(this);

        initTimer();

        scannerGunManager = new ScannerGunManager(new ScannerGunManager.OnScanListener() {
            @Override
            public void onResult(String code) {
                Toast.makeText(FullscreenActivity.this, "扫描枪：" + code, Toast.LENGTH_SHORT).show();
                expressBillNum = code;
                new OpenCabinetByExpressTask(code).execute();
            }
        });

        //OtherUtil.getDensityDpi(this);

        // 捕捉异常
        /*MyCatchException mException=MyCatchException.getInstance();
        mException.init(getApplicationContext());*/

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                SerialPortWorker.serialHelper = new SerialPortHelper();
                try{

                    SerialPortWorker.serialHelper.open();
                    String uid = OtherUtil.getUID(FullscreenActivity.this);
                    //new RedisWorker(redisIp,redisPort,redisPwd,uid).start();
                    new RedisWorker("120.77.149.44",6379,"123456","100001").start();
                    new Thread(new MessageConsumer()).start();

                    new SerialPortReadWorker().start();
                    new SerialPortWriteWorker().start();

                }catch (Exception e){
                    e.printStackTrace();
                    finish();
                }
            }
        }).start();*/

        /*final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.postDelayed(this, 30000);
                //每隔一段时间要重复执行的代码
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        jedis.close();
                        jedis.connect();

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }

                        consumerMessage();
                    }
                }).start();
            }
        };
        handler.postDelayed(runnable, 30000);*/
        initTimerReboot();

        new Thread(new Runnable() {
            @Override
            public void run() {
                SerialPortWorker.serialHelper = new SerialPortHelper();
                //SerialPortWorker.serialHelper.setPort("/dev/ttyS1");
                try{

                    SerialPortWorker.serialHelper.open();
                    WebSocketClient.connect("ddhg.xmxbox.com"); // 发起连接 120.77.149.44
                    Log.d("WebSocketClient","发起连接");
                    new SerialPortReadWorker().start();
                    new SerialPortWriteWorker().start();

                }catch (Exception e){
                    e.printStackTrace();
                    finish();
                }
            }
        }).start();

        startTimeTask();

        final NetworkConnectChangedReceiver mNetworkChangeListener = new NetworkConnectChangedReceiver();

        //网络版需要监听网络状态
        CountDownTimer timer = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                /*IntentFilter filter2 = new IntentFilter();
                filter2.addAction("android.net.conn.CONNECTIVITY_CHANGE");
                filter2.addAction("android.net.wifi.WIFI_STATE_CHANGED");
                filter2.addAction("android.net.wifi.STATE_CHANGE");
                filter2.addAction("android.intent.action.MEDIA_MOUNTED");
                filter2.addDataScheme("file");
                registerReceiver(netReciver,filter2);*/
                IntentFilter filter = new IntentFilter();
                filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
                filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
                filter.addAction("android.net.wifi.STATE_CHANGE");
                registerReceiver(mNetworkChangeListener,filter);
            }
        };
        timer.start();
    }

    private void initTimerReboot() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String curTime = OtherUtil.getTime();
                if (curTime.contains("07:00:")) {
                    LogUtil.getInstance().info("每日重启" + curTime);
                    Log.e("redis日志", "每日重启" + curTime);
                    Intent intent = new Intent();
                    intent.setClass(FullscreenActivity.this,Qj1Activity.class);
                    intent.putExtra("isRestart", true);
                    startActivity(intent);
                }

            }
        }, 60000, 30000);
    }

    public class NetworkConnectChangedReceiver extends BroadcastReceiver {

        private static final String TAG = "xujun";
        public static final String TAG1 = "xxx";
        @Override
        public void onReceive(Context context, Intent intent) {
            // 这个监听wifi的打开与关闭，与wifi的连接无关
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                Log.e(TAG1, "wifiState" + wifiState);
                switch (wifiState) {
                    case WifiManager.WIFI_STATE_DISABLED:
                        Log.e(TAG1, "wifiState" + false);
                        break;
                    case WifiManager.WIFI_STATE_DISABLING:

                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        break;
                    case WifiManager.WIFI_STATE_ENABLED:
                        Log.e(TAG1, "wifiState" + true);
                        break;
                    case WifiManager.WIFI_STATE_UNKNOWN:
                        break;
                    default:
                        break;


                }
            }
            // 这个监听wifi的连接状态即是否连上了一个有效无线路由，当上边广播的状态是WifiManager
            // .WIFI_STATE_DISABLING，和WIFI_STATE_DISABLED的时候，根本不会接到这个广播。
            // 在上边广播接到广播是WifiManager.WIFI_STATE_ENABLED状态的同时也会接到这个广播，
            // 当然刚打开wifi肯定还没有连接到有效的无线
            if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                Parcelable parcelableExtra = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (null != parcelableExtra) {
                    NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
                    NetworkInfo.State state = networkInfo.getState();
                    boolean isConnected = state == NetworkInfo.State.CONNECTED;// 当然，这边可以更精确的确定状态
                    Log.e(TAG1, "isConnected" + isConnected);
                }
            }
            // 这个监听网络连接的设置，包括wifi和移动数据的打开和关闭。.
            // 最好用的还是这个监听。wifi如果打开，关闭，以及连接上可用的连接都会接到监听。见log
            // 这个广播的最大弊端是比上边两个广播的反应要慢，如果只是要监听wifi，我觉得还是用上边两个配合比较合适
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                ConnectivityManager manager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                Log.i(TAG1, "CONNECTIVITY_ACTION");

                NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
                if (activeNetwork != null) { // connected to the internet
                    if (activeNetwork.isConnected()) {
                        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                            // connected to wifi
                            Log.e(TAG, "当前WiFi连接可用 ");
                            if (isForeground(FullscreenActivity.this,ErrorActivity.class.getName())) {
                                if(ErrorActivity.errorActivity!=null){
                                    ErrorActivity.errorActivity.finish();
                                }
                            }
                        } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                            // connected to the mobile provider's data plan
                            Log.e(TAG, "当前移动网络连接可用 ");
                            if (isForeground(FullscreenActivity.this,ErrorActivity.class.getName())) {
                                if(ErrorActivity.errorActivity!=null){
                                    ErrorActivity.errorActivity.finish();
                                }
                            }
                        }
                    } else {
                        Log.e(TAG, "当前没有网络连接，请确保你已经打开网络 ");
                        Intent intent1 = null;
                        intent1 = new Intent(FullscreenActivity.this, ErrorActivity.class);
                        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent1);
                    }


                    Log.e(TAG1, "info.getTypeName()" + activeNetwork.getTypeName());
                    Log.e(TAG1, "getSubtypeName()" + activeNetwork.getSubtypeName());
                    Log.e(TAG1, "getState()" + activeNetwork.getState());
                    Log.e(TAG1, "getDetailedState()"
                            + activeNetwork.getDetailedState().name());
                    Log.e(TAG1, "getDetailedState()" + activeNetwork.getExtraInfo());
                    Log.e(TAG1, "getType()" + activeNetwork.getType());
                } else {   // not connected to the internet
                    Log.e(TAG, "当前没有网络连接，请确保你已经打开网络 ");
                    Intent intent1 = null;
                    intent1 = new Intent(FullscreenActivity.this, ErrorActivity.class);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent1);

                }
            }
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context Activity的getAppliction()获取
     * @param className Activity名称 由类名.class.getName()获取
     *
     */
    private boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (scannerGunManager.dispatchKeyEvent(event)) {
            return true;
        }

        return super.dispatchKeyEvent(event);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    @Override
    public void setMessage(String myTopic, String message) {

    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                //更新时间
                dateText.setText(TimeUtils.getStringDateShort(new Date()));
            }
        }
    };

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "收到广播", Toast.LENGTH_SHORT).show();
        }
    }

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action))
            {
                synchronized (this)
                {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                    {
                    }
                    else
                    {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };
    private void RequestDevicePermission() {


        //IntentFilter filter = new IntentFilter();
        //myReceiver = new MyReceiver();
        //mContext.registerReceiver(myReceiver,filter );
//        mContext = this.getApplicationContext();
//        musbManager = (UsbManager)this.getSystemService(Context.USB_SERVICE);
//        myReceiver = new MyReceiver();
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(ACTION_USB_PERMISSION);
//        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
//        mContext.registerReceiver(mUsbReceiver, filter);
//        //mContext.registerReceiver(myReceiver, );
//
//        for (UsbDevice device : musbManager.getDeviceList().values())
//        {
//            if (device.getVendorId() == VID && device.getProductId() == PID)
//            {
//                Intent intent = new Intent(ACTION_USB_PERMISSION);
//                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
//                musbManager.requestPermission(device, pendingIntent);
//            }
//        }
    }
    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;


    }

    @SuppressLint("InlinedApi")
    private void show() {
        mVisible = true;


    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    //work
    private void initTimer(){


        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {


                //前端保持
                keepForeground();
                //心跳保持
                keepHeartBeat();
                //判断消息通知
                //recvNotify();
            }
        },0,1000);


    }
    private void keepHeartBeat(){
        /*try{

        }catch (Exception e){
            LogUtil.getInstance().info(e.toString());
        }*/

        String curTime = OtherUtil.getTime();
        if(curTime.indexOf("30:00") != -1){
            new FetchHeartBeatTask().execute();
        }

        /*if (curTime.contains("00:00:00")) {
            *//*LogUtil.getInstance().info("每日重启" + curTime);
            Intent intent = new Intent();
            intent.setClass(FullscreenActivity.this,Qj1Activity.class);
            intent.putExtra("isRestart", true);
            startActivity(intent);*//*

            *//*Date d = new Date();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            String datestr = sf.format(d);
            dateText.setText(datestr);*//*
        }*/

    }

    private void keepForeground(){
        //判断前台还是后台
        if (!FullscreenActivity.this.isFinishing()) {
            if(OtherUtil.isBackground(getApplicationContext())){
                Log.d("active ", "false");
                activecount++;
                if(activecount > 20){
                    //OtherUtil.restartApplication(FullscreenActivity.this);

                    Intent intent = new Intent();
                    intent.setClass(FullscreenActivity.this,Qj1Activity.class);
                    intent.putExtra("isRestart", true);
                    startActivity(intent);
                }
            }else{
                activecount = 0;
                adShow();
                Log.d("active ", "true");
            }
        }
    }
    private void handleSerialNotify(Object obj){
        try{
            String value = obj.toString();

            JSONObject notify = new JSONObject(value);

            new FetchReturnOpenGridCmdTask(value).execute();
            int _io = notify.getJSONObject("data").getInt("IO");
            int _485 = notify.getJSONObject("data").getInt("485");
            if(_io == 0 && _485 == 250){
                return ;
            }



            if(notify.getJSONObject("data").getString("type").equals("RE_LOCAL_QJ_OPEN_GRID")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("reopen",value);
                editor.apply();
                Message message = new Message();
                message.what=10202;
                message.obj=value;
                EventBus.getDefault().post(message);
            }else if(notify.getJSONObject("data").getString("type").equals("RE_LOCAL_JJ_REOPEN_GRID")){

                Message message = new Message();
                message.what=10410;
                message.obj=value;
                EventBus.getDefault().post(message);
            }else if(notify.getJSONObject("data").getString("type").equals("RE_LOCAL_JJ_OPEN_GRID")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("reopen",value);
                editor.apply();
                Message message = new Message();
                message.what=10108;
                message.obj=value;
                EventBus.getDefault().post(message);
            }else if(notify.getJSONObject("data").getString("type").equals("RE_LOCAL_KD_OPEN_GRID")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("reopen",value);
                editor.apply();
                Message message = new Message();
                message.what=10422;
                message.obj=value;
                EventBus.getDefault().post(message);
            }



        }catch (Exception e){
            e.printStackTrace();
        }

    }



    private void adShow(){
        if(adcount < 10){

            if(adcount == 0){
                adcount = 20;
                Message msg = new Message();
                msg.what = 10004;
                EventBus.getDefault().post(msg);
            }
            adcount = adcount - 1;
        }
        if(adcount >= 10){

            if(adcount == 10){

                Message msg = new Message();
                msg.what = 10004;
                EventBus.getDefault().post(msg);

            }
            adcount = adcount - 1;
        }
    }

    private void initControl(FullscreenActivity activity){
        Button  welcome_recv_img = findViewById(R.id.welcome_recv_img);
        welcome_recv_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    intent.setClass(FullscreenActivity.this,QjMainActivity.class);
                    //TODO:入口测试
                    //intent.setClass(FullscreenActivity.this,Kd7Activity.class);
                    startActivityForResult(intent, 1);

                }
            }
        });


        Button  welcome_send_img = findViewById(R.id.welcome_send_img);
        welcome_send_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:Test
                //AddressModule addressModule = null;
                //addressModule.getUserId();

                //CrashReport.testJavaCrash();

                /*try {
                    CrashReport.testJavaCrash();
                } catch (Exception e) {
                    LogUtil.getInstance().info(e.toString());
                }*/

                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    // do something
                    Message msg = new Message();
                    msg.what = 1007;
                    EventBus.getDefault().post(msg);

                }
            }
        });


        Button  welcome_zc_img = findViewById(R.id.welcome_zc_save);
        welcome_zc_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDevelopmentDialog();
            }
        });
        welcome_kd_enter = findViewById(R.id.kdenter);
        welcome_kd_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - mLastClickTime > TIME_INTERVAL) {
                    mLastClickTime = nowTime;
                    Intent intent = new Intent();
                    intent.setClass(FullscreenActivity.this, ExpressmanMainActivity.class);
                    startActivityForResult(intent, 1);
                }
            }
        });
        RelativeLayout verText = (RelativeLayout)findViewById(R.id.full_logo);
        verText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(settingcount > 8){
                    settingcount = 0;
//                    if(OtherUtil.isRoot()){
//                        OtherUtil.silentInstall("/storage/emulated/0/Download/TeamViewerHost.apk");
//                    }
//                    Intent intent =  new Intent(Settings.ACTION_SETTINGS);
//                    startActivity(intent);
                    Message message = new Message();
                    message.what=1;
                    EventBus.getDefault().post(message);
                }else{
                    settingcount ++;
                }

            }
        });
    }

    private void showDevelopmentDialog() {
        View view = View.inflate(this, R.layout.dialog_development, null);
        initDialogView(view);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(500), OtherUtil.dp2px(560),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initDialogView(View view) {
        btn_confirm = view.findViewById(R.id.btn_confirm);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

    private void initView(FullscreenActivity activity){

    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        if(curEventCode != 0 ){
            long nowTime = System.currentTimeMillis();
            if ((nowTime - curLastEventTime < EVENT_TIME_INTERVAL )&& curEventCode == message.what) {
                Toast.makeText(FullscreenActivity.this, "防止重入", Toast.LENGTH_SHORT).show();
                return ;
            }else{
                curEventCode = message.what;
            }
        }
        switch(message.what){
            case 1:
                intent.setClass(FullscreenActivity.this,SettingActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 1000:
                intent.setClass(FullscreenActivity.this,Qj1Activity.class);
                intent.putExtra("isRestart", true);
                startActivity(intent);
                break;
            case 1001:
                intent.setClass(FullscreenActivity.this,ChoosePostWayActivity.class);
                //intent.setClass(FullscreenActivity.this,JjResultActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 1002:
                intent.putExtra("isFromWX", (boolean) message.obj);
                intent.setClass(FullscreenActivity.this,Jj3NewActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 1003:
                intent.setClass(FullscreenActivity.this,Jj3WXActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 1004:
                if ((boolean) message.obj == false) {
                    intent.setClass(FullscreenActivity.this,Jj3NewActivity.class);
                    intent.putExtra("isFromWX", (int)message.arg1 == 1 ? true : false);
                } else {
                    intent.setClass(FullscreenActivity.this,Jj3Activity.class);
                }
                startActivityForResult(intent, 1);
                break;
            case 1005:
                intent.putExtra("isFromWX", (boolean) message.obj);
                intent.setClass(FullscreenActivity.this,Jj4Activity.class);
                startActivityForResult(intent, 1);
                break;
            case 1006:
                intent.setClass(FullscreenActivity.this,JjResultActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 1007:
                intent.setClass(FullscreenActivity.this,KdRegActivity.class);
                startActivityForResult(intent, 1);
                break;
             case 1008:
                intent.setClass(FullscreenActivity.this,JjFaceActivity.class);
                intent.putExtra("mBoxType", (int)message.obj);
                intent.putExtra("isFromWX", (int)message.arg1 == 1 ? true : false);
                startActivityForResult(intent, 1);
                break;
            case 1009:
                Bundle bundle = new Bundle();
                bundle.putSerializable("logisticModule", (Serializable) message.obj);
                intent.putExtras(bundle);
                intent.setClass(FullscreenActivity.this,ChooseLogicActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 2000:
            case 2001:
                intent.setClass(FullscreenActivity.this,QjResultActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 2002:
                intent.setClass(FullscreenActivity.this,Qj1Activity.class);
                startActivity(intent);
                break;
            case 2003:
            case 2004:
                break;
            case 4001:
                intent.setClass(FullscreenActivity.this, ExpressmanMainActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 4002:

                //OtherUtil.restartApplication(FullscreenActivity.this);
                break;
            case 4003:
                intent.setClass(FullscreenActivity.this,Kd3Activity.class);
                startActivityForResult(intent, 1);
                break;
            case 4004:
                intent.setClass(FullscreenActivity.this, DeliverActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 4005:
                intent.setClass(FullscreenActivity.this, ExpressmanMainActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 4006:
                intent.setClass(FullscreenActivity.this,Kd5Activity.class);
                String str1 = message.getData().getString("kd_lj_name");//接受msg传递过来的参数
                String str2 = message.getData().getString("kd_lj_cardid");//接受msg传递过来的参数
                intent.putExtra("kd_lj_name", str1);
                intent.putExtra("kd_lj_cardid", str2);
                startActivityForResult(intent, 1);
                break;
            case 4007:
                intent.setClass(FullscreenActivity.this,Kd4Activity.class);
                startActivityForResult(intent, 1);
                break;
            case 4008:
                intent.setClass(FullscreenActivity.this,Kd3Activity.class);
                startActivityForResult(intent, 1);
                break;
            case 4009:
                intent.setClass(FullscreenActivity.this,Kd5Activity.class);
                startActivityForResult(intent, 1);
                break;
            case 4010:
                intent.setClass(FullscreenActivity.this,Kd6Activity.class);
                startActivityForResult(intent, 1);
                break;
            case 4011:

                break;
            case 4012:
                intent.setClass(FullscreenActivity.this,Kd7Activity.class);
                String str3 = message.getData().getString("kd_lj_name");//接受msg传递过来的参数
                String str4 = message.getData().getString("kd_lj_cardid");//接受msg传递过来的参数
                intent.putExtra("kd_lj_name", str3);
                intent.putExtra("kd_lj_cardid", str4);
                startActivityForResult(intent, 1);
                break;
            case 4013:

                break;
            case 4014:
                intent.setClass(FullscreenActivity.this,KdFaceActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 4015:
                intent.setClass(FullscreenActivity.this,ExpressmanMainActivity.class);
                startActivityForResult(intent, 1);
                break;
            case 5001:
                handleRed(message.obj);
                break;
            case 10000:
                //handleGetCabinetType(message.obj);
                break;
            case 10001:
                //Toast.makeText(FullscreenActivity.this, "获取柜子类型失败", Toast.LENGTH_SHORT).show();
                handleReGetCabinetType();
                break;
            case 10002:
                handleNetworkReConect();
                break;
            case 10003:
                //handleNetworkError();
                break;
            case 10004:
                handleAdShow();
                break;
            case 10005:
                handleSerialNotify(message.obj);
                break;
            case 5555:
                dateText.setText(message.obj.toString());
                break;
            case 6666:
                dateText.setText(message.obj.toString());
                break;
            case 7777:
                recShow.setText(recShow.getText().toString() + "\n" + message.obj.toString());
                break;
            case 8888:
                sendShow.setText(sendShow.getText().toString() + "\n" + message.obj.toString());
                break;
            case 9999:
                logShow.setText(logShow.getText().toString() + message.obj.toString());
                break;
        }
    }

    private void handleRed(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                Intent intent = new Intent();
                new FetchOpenLocalGridTaskByRed(obj.toString()).execute();
                intent.setClass(FullscreenActivity.this, FinishDeliverActivity.class);
                intent.putExtra("expressBillNum", expressBillNum);
                intent.putExtra("cabinetgridid", result.getJSONObject("data").getString("cabinetGridId"));
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(), result.getString("msg"), Toast.LENGTH_LONG).show();

                if (result.getString("msg").contains("余额不足")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(FullscreenActivity.this);
                    View view = View
                            .inflate(FullscreenActivity.this, R.layout.notic_dialog, null);
                    ImageView iv = view.findViewById(R.id.tv_cycler);
                    SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                    String cnImage     =  sharedPreferences.getString("CabinetType_gzh","");
                    new FetchUrlImageTask(cnImage,iv).execute();

                    builder.setView(view);
                    builder.setCancelable(true);

                    AlertDialog dialog = builder.create();
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.show();
                }
            }
        }
        catch (Exception e){

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode > 0){
            try{
                Message message = new Message();
                message.what=resultCode;
                if (resultCode == 1002 || resultCode == 1005) {
                    message.obj=data.getBooleanExtra("isFromWX", false);
                } else if (resultCode == 1004) {
                    message.obj=data.getBooleanExtra("isFromCainiao", false);
                    message.arg1=data.getIntExtra("isFromWX", 0);
                } else if (resultCode == 1009) {
                    message.obj=(ArrayList<LogisticModule>) data.getSerializableExtra("logisticModule");
                } else if (resultCode == 1008) {
                    message.obj=data.getIntExtra("mBoxType", 0);
                    message.arg1=data.getIntExtra("isFromWX", 0);
                } else if (resultCode == 4012 || resultCode == 4006) {
                    Bundle bundle = new Bundle();
                    bundle.putString("kd_lj_name",data.getStringExtra("kd_lj_name"));
                    bundle.putString("kd_lj_cardid",data.getStringExtra("kd_lj_cardid"));
                    message.setData(bundle);
                }

                EventBus.getDefault().post(message);
            }catch (Exception e)
            {

            }

        }
    }
    private void handleReGetCabinetType(){
        String uid = OtherUtil.getUID(this);
        new FetchgetCabinetType(uid).execute();
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String address = sharedPreferences.getString("CabinetType_address","");
        String phone = sharedPreferences.getString("CabinetType_phone","");
        addrText.setText(address);
        addrLine.setText("客服电话:" + phone);
    }
    private void handleGetCabinetType(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                String phone = result.getJSONObject("data").getString("phone");
                String kuai = result.getJSONObject("data").getString("kuai");
                String cai = result.getJSONObject("data").getString("cai");
                String cai_phone = result.getJSONObject("data").getString("courier");
                String gzh = result.getJSONObject("data").getString("gzh");
                String gz = result.getJSONObject("data").getString("number");
                String address = result.getJSONObject("data").getString("address");
                String serviceline = result.getJSONObject("data").getString("serviceline");
                final String redisPwd = result.getJSONObject("data").getString("RedisPwd");
                final String redisIp = result.getJSONObject("data").getString("IP");
                final int redisPort = result.getJSONObject("data").getInt("Port");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putString("CabinetType_phone",phone);
                editor.putString("CabinetType_kuai",kuai);
                editor.putString("CabinetType_cai",cai);
                editor.putString("CabinetType_cai_phone",cai_phone);
                editor.putString("CabinetType_gzh",gzh);
                editor.putString("CabinetType_gz",gz);
                editor.putString("CabinetType_address",address);
                editor.putString("CabinetType_serviceline",serviceline);
                editor.apply();
                addrText.setText(address);
                addrLine.setText("客服电话:" + phone);

                SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                String cnImage     =  sharedPreferences.getString("CabinetType_gzh","");
                String gzImage     =  sharedPreferences.getString("CabinetType_gz","");
                new FetchUrlImageTask(cnImage,gzh_qrcode).execute();
                new FetchUrlImageTask(gzImage,gz_qrcode).execute();
                LogUtil.getInstance().info("Start and FetchUrlImageTask");
                //init

                //MainContext = this.getApplicationContext();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SerialPortWorker.serialHelper = new SerialPortHelper();
                        try{

                            SerialPortWorker.serialHelper.open();
                            String uid = OtherUtil.getUID(FullscreenActivity.this);
                            //new RedisWorker(redisIp,redisPort,redisPwd,uid).start();
                            new RedisWorker("121.37.251.46",6379,"hc5922497","100002").start();
                            new Thread(new MessageConsumer()).start();

                            new SerialPortReadWorker().start();
                            new SerialPortWriteWorker().start();

                        }catch (Exception e){
                            e.printStackTrace();
                            finish();
                        }
                    }
                }).start();
            }
        }
        catch (Exception e){

        }
    }

    private void handleNetworkError(){
        if(!isErrorStatus()) {
            startActivity(new Intent(FullscreenActivity.this, ErrorActivity.class));
        }
    }
    private void handleNetworkReConect(){
        if(isErrorStatus()){
            //OtherUtil.restartApplication(this);
            String curTime = OtherUtil.getTime();
            LogUtil.getInstance().info("网络错误重启" + curTime);
            Intent intent = new Intent();
            intent.setClass(FullscreenActivity.this,Qj1Activity.class);
            intent.putExtra("isRestart", true);
            startActivity(intent);
        }

    }
    private boolean isErrorStatus(){
        ActivityManager am = (ActivityManager) this
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);

        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            return topActivity.getClassName().equals(
                    ErrorActivity.class.getName());
        }
        return false;
    }

    private void handleAdShow(){
        ImageView  welcome_gg = (ImageView) findViewById(R.id.welcome_gg);
        if(adcount > 10){
            welcome_gg.setImageResource(R.mipmap.ad1);
        }else{
            welcome_gg.setImageResource(R.mipmap.ad2);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        timedTask.dispose();
    }

    @Override
    protected void onStop() {
        super.onStop();

    }
}
